package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.apache.ibatis.annotations.Delete;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$") String password) {

            User user = userService.findByUsername(username);
            if (user != null) {
                return Result.error("用户名已存在");
            }else {
                userService.register(username, password);
                return Result.success();
            }
        }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,
                        @Pattern(regexp = "^\\S{5,16}$") String password){
        User user = userService.findByUsername(username);
        if (user == null) {
            return Result.error("用户名错误");
        }
        if(Md5Util.getMD5String(password).equals(user.getPassword())){
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("username", user.getUsername());
            map.put("id", user.getId());
            String token = JwtUtil.genToken(map);
            String oldToken = user.getId()+user.getUsername();
            redisTemplate.delete(oldToken);
            redisTemplate.opsForValue().set(user.getId()+user.getUsername(),
            token,60 * 60 * 24 * 7, TimeUnit.SECONDS);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result getUserInfo(){
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody @Validated User user){
        userService.updateUser(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map,@RequestHeader("Authorization") String token){
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd)
                || !StringUtils.hasLength(rePwd)){
           return Result.error("参数错误");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        Map<String, Object> clams = ThreadLocalUtil.get();
        String username = (String) clams.get("username");
        Integer id = (Integer) clams.get("id");
        String oldToken = id+username;
        User user = userService.findByUsername(username);
        if(!Md5Util.getMD5String(oldPwd).equals(user.getPassword())){
            return Result.error("原密码错误");
        }
        newPwd = Md5Util.getMD5String(newPwd);
        userService.updatePwd(newPwd);
        redisTemplate.delete(oldToken);
        return Result.success();
    }

    @DeleteMapping("/delete")
    public Result deleteUser(){
        Map<String, Object> clams = ThreadLocalUtil.get();
        String username = (String) clams.get("username");
        Integer id = (Integer) clams.get("id");
        String oldToken = id+username;
        redisTemplate.delete(oldToken);
        return Result.success();
    }
    }


